import 'dart:async';

import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/common/class/audio/index.dart';
import 'package:qgchat/common/class/websocket/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/apis/video.dart';
import 'package:qgchat/http/models/anchorInfoModel.dart';
import 'package:qgchat/http/models/listuserInfoModel.dart';
import 'package:qgchat/http/models/tokenuserInfoModel.dart';
import 'package:qgchat/states/states_model/socket.dart';
import 'package:qgchat/states/states_model/user.dart';
import 'package:wakelock/wakelock.dart';


class AnswerPhoneBloc implements BlocBase {
  // ##########  STREAMS  ##############

  /// 对方用户类型是否主播
  StreamController _userTypeAnchor = StreamController<bool>.broadcast();
  Sink get _userTypeSink => _userTypeAnchor.sink;
  Stream get userTypeStream => _userTypeAnchor.stream;

  /// 获取用户在该主播的消费
  StreamController _consume = StreamController<ListuserInfoModel>.broadcast();
  Sink get _consumeSink => _consume.sink;
  Stream get consumeStream => _consume.stream;

  /// 主播的时光价值
  StreamController _cost = StreamController<AnchorInfoModel>.broadcast();
  Sink get _costSink => _cost.sink;
  Stream get costStream => _cost.stream;

  // ##########  DEFAULT  ##############

  /// 获取用户在该主播的消费 默认值
  final ListuserInfoModel consumeDefault =
      ListuserInfoModel(money: 0, gold1: 0);

  /// 主播的时光价值 默认值
  final AnchorInfoModel costDefault = AnchorInfoModel(timePrice: 0);

  // ##########  HANDLING  ##############

  /// 是否已经接听
  bool isAccept = false;

  /// websocket
  WebSocket ws = Global.ws;

  AnswerPhoneBloc(targetToken, targetInv) {
    ws?.listenStoptalk = targetCloseVideo; // 监听远端用户挂断或拒绝

    Wakelock.enable(); // 屏幕常亮
    _userInfo(targetToken);

    playAudioAndWaitClose(targetInv, targetToken);
  }

  /// 销毁
  void dispose() {
    Wakelock.disable(); // 关闭屏幕常亮
    
    Global.audio.stopAllAudio();

    SocketState socketState = state(Global.context, 'socket');
    socketState.toggleCallState(false);

    _userTypeAnchor.close();
    _consume.close();
    _cost.close();
  }

  /// 获取用户信息
  _userInfo(targetToken) async {
    UserState userState = (state(Global.context, 'user') as UserState);
    TokenuserInfoModel userInfo = await VideoApis.tokenuserInfo(targetToken);
    // 对方是主播
    if (!_userTypeAnchor.isClosed) {
      if (userInfo.memberType == 1) {
        _userTypeSink.add(true);
        AnchorInfoModel anchorInfo =
            await UserApis.topbigVintroduce(targetToken);
        if (!_cost.isClosed) {
          _costSink.add(anchorInfo);
        }
      } else {
        // 对方是用户
        _userTypeSink.add(false);
        ListuserInfoModel userPay = await VideoApis.listuserInfo(
          userState.info.memberToken,
          targetToken,
        );
        if (!_consume.isClosed) {
          _consumeSink.add(userPay);
        }
      }
    }
  }

  /// 播放铃声，并且在一定时间未反应自动关闭
  void playAudioAndWaitClose(targetInv, targetToken) {
    print(2222);
    Global.audio.loop(Audios.VideoCall, callback: () {
      if (!isAccept && !_userTypeAnchor.isClosed) {
        refuse(
          targetToken: targetToken,
          inv: targetInv,
          tips: "长时间未应答，自动拒绝通话",
        );
      }
    });
  }

  /// 接听通话
  void accept(
    context,
    isAnchor,
    targetInv,
    userId,
    anchorId,
    targetName,
    targetHead,
    targetToken,
  ) {
    Global.ws.sendInvtokening(targetInv);

    isAccept = true;
    UserState user = state(context, 'user');
    // dispose();
    // Navigator.pushReplacement(context, MaterialPageRoute(
    //   builder: (BuildContext context) {
    //     return BlocProvider(
    //       bloc: LiveBloc(
    //         inv: targetInv,
    //         aid: anchorId,
    //         uid: userId,
    //         targetToken: targetToken,
    //         targetName: targetName,
    //         targetHead: targetHead,
    //         isReceive: true,
    //         isAnchor: isAnchor,
    //       ),
    //       child: Live(
    //         isAnchor,
    //         true,
    //         targetInv,
    //         userId,
    //         anchorId,
    //         targetName,
    //         targetHead,
    //         targetToken,
    //       ),
    //     );
    //   }
    // ));
    // Navigator.of(context).pop();
    Global.audio.stopAllAudio();
    goPage(context, '/live', param: {
      'targetInv': targetInv,
      'isAnchor': user.info.memberType == 1,
      'isReceive': true,
      'userId': userId,
      'anchorId': anchorId,
      'targetName': targetName,
      'targetHead': targetHead,
      'targetToken': targetToken,
    });
  }

  /// 拒绝通话
  void refuse({
    String targetToken,
    int inv,
    String tips = '已拒绝对方的通话请求',
  }) {
    // Global.ws.refuseVideo(inv);
    Global.ws.stoptalk(targetToken);

    showToast(tips);
    Global.noCtxRoute.navigateBack();
  }

  /// 对方停止了通话请求
  void targetCloseVideo() {
    showToast("对方结束了通话请求");
    Global.noCtxRoute.navigateBack();
  }
}
